package com.zbw.printlibrary.printSub;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.landi.print.service.ICallback;
import com.landi.print.service.IPrintService;
import com.landi.print.service.PrintBinder;
import com.landicorp.financekit.cashbox.CashBoxBinder;
import com.landicorp.financekit.cashbox.ICashBox;
import com.zbw.printlibrary.bean.AttributeBean;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.PrinterControlCommon;
import com.zbw.printlibrary.util.PrintThreadPoolManager;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cyj on 2019-07-24.
 * 联迪打印
 */

public class PrintLiandi extends PrinterControlCommon {

    // 联迪打印
    private IPrintService printService = null;
    private Context mContext;
    private IPrintCallBack mCallBack;
    private ICashBox mCashBoxService;

    public PrintLiandi(@NonNull Context context, IPrintCallBack callback) {
        mContext = context;
        this.mCallBack = callback;
        connectOpenBox();
    }

    /**
     * 开钱箱
     */
    public void connectOpenBox() {
        if (mCashBoxService == null) {
            try {
                Intent intent = new Intent();
                CashBoxBinder.bindService(mContext, intent, connServiceBox, Context.BIND_AUTO_CREATE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void connectPrinter() {

        try {
            if (printService == null) {
                Intent intent = new Intent();
                boolean result = PrintBinder.bindPrintService(mContext, intent, connService, Context.BIND_AUTO_CREATE);
                Log.d("tag", "bind result:" + result);
            }
        } catch (Exception e) {
            Toast.makeText(mContext, "没有找到联迪模块", Toast.LENGTH_SHORT).show();
            mCallBack.onConnect("连接失败", false);
            e.printStackTrace();
        }

    }

    @Override
    public void disConnectPrinter() {
        try {
            mContext.unbindService(connService);
            mContext.unbindService(connServiceBox);
            mCallBack.onDisConnect("断开成功", true);
            if (mContext != null) {
                mContext = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onDisConnect("断开失败", false);
        }
    }

    @Override
    public void printTest(final List<String> testList) {
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    printService.printerInit();
                    printService.enterPrinterBuffer(true);
                    printService.setAlignment(1, null);
                    printService.printTextWithFont(testList.get(0) + "\n", "", 48, null);
                    printService.printTextWithFont(testList.get(1) + "\n", "", 36, null);
                    printService.setAlignment(0, null);
                    for (int i = 2; i < testList.size(); i++) {
                        printService.printTextWithFont(testList.get(i) + "\n", "", 24, null);
                    }
                    printService.lineWrap(1, null);
                    printService.cutPaper(null);

                    printService.exitPrinterBufferWithCallback(true, new ICallback.Stub() {
                        @Override
                        public void onPrintResult(boolean success, int code, String msg) throws RemoteException {
                            if (success) {
                                mCallBack.onPrintResult(true);
                            } else {
                                mCallBack.onPrintResult(false);
                            }
                        }
                    });
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    mCallBack.onPrintResult(false);
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void printString(final List<AttributeBean> testList) {
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    printService.printerInit();
                    printService.enterPrinterBuffer(true);
                    for (int i = 0; i < testList.size(); i++) {
                        float fontSize = 0;
                        String line = "";
                        switch (testList.get(i).getFont_size()) {
                            case 0:
                                fontSize = 24;
                                break;
                            case 1:
                                fontSize = 36;
                                break;
                            case 2:
                                fontSize = 48;
                                break;
                        }
                        if (testList.get(i).isFont_line()) {
                            line = "\n";
                        }
                        printService.setAlignment(testList.get(i).getFont_gray(), null);
                        if (1 == testList.get(i).getContext_type()) {
                            printService.printBitmap(testList.get(i).getBitmap(), null);
                        } else {
                            printService.printTextWithFont(testList.get(i).getContext() + line, "", fontSize, null);
                        }

                    }
                    printService.lineWrap(1, null);
                    printService.cutPaper(null);

                    printService.exitPrinterBufferWithCallback(true, new ICallback.Stub() {
                        @Override
                        public void onPrintResult(boolean success, int code, String msg) throws RemoteException {
                            if (success) {
                                mCallBack.onPrintResult(true);
                            } else {
                                mCallBack.onPrintResult(false);
                            }
                        }
                    });
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    mCallBack.onPrintResult(false);
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * @param testList
     * @param bitmapHashMap 在key位置后打印bitmap  position大于list的话默认在最后打印bitmap
     */
    @Override
    public void printStringAndBitmap(final List<String> testList, final LinkedHashMap<Integer, Bitmap> bitmapHashMap) {
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    printService.printerInit();
                    printService.enterPrinterBuffer(true);
                    for (int i = 0; i < testList.size(); i++) {
                        String message = testList.get(i);
                        switch (i) {
                            case 0:
                                printService.setAlignment(1, null);
                                printService.printTextWithFont(message + "\n", "", 48, null);
                                break;
                            case 1:
                                printService.setAlignment(1, null);
                                printService.printTextWithFont(message + "\n", "", 36, null);
                                break;
                            default:
                                if (message.startsWith("牌号")) {
                                    //牌号放大打印
                                    printService.setAlignment(0, null);
                                    printService.printTextWithFont(message + "\n", "", 36, null);
                                } else {
                                    printService.setAlignment(0, null);
                                    printService.printTextWithFont(message + "\n", "", 24, null);
                                }
                                break;
                        }
                        Bitmap bitmap = bitmapHashMap.get(i);
                        if (bitmap != null) {
                            //当前位置与需要打印位置一致 打印bitmap
                            printService.setAlignment(1, null);
                            printService.printBitmap(bitmap, null);
                        }
                    }
                    if (bitmapHashMap.size() > 0) {
                        printService.setAlignment(1, null);
                        //传入的position位置大于list的话默认在最后面打印
                        for (Map.Entry<Integer, Bitmap> entry : bitmapHashMap.entrySet()) {
                            if (entry.getKey() > testList.size() - 1) {
                                Bitmap showBitmap = entry.getValue();
                                printService.printBitmap(showBitmap, null);
                            }
                        }
                    }
                    printService.lineWrap(1, null);
                    printService.cutPaper(null);
                    printService.exitPrinterBufferWithCallback(true, new ICallback.Stub() {
                        @Override
                        public void onPrintResult(boolean success, int code, String msg) throws RemoteException {
                            if (success) {
                                mCallBack.onPrintResult(true);
                            } else {
                                mCallBack.onPrintResult(false);
                            }
                        }
                    });
                } catch (Exception e) {
                    mCallBack.onPrintResult(false);
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public void blueConnect(String address) {

    }

    @Override
    public void disBlueConnect() {

    }


    @Override
    public void openMoneyBox() {
        try {
            if (mCashBoxService != null) {
                mCashBoxService.openBox();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean isConnected() {
        if (printService == null) {
            return true;
        } else {
            return false;
        }
    }

    public ServiceConnection connServiceBox = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mCashBoxService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mCashBoxService = ICashBox.Stub.asInterface(service);
        }
    };

    public ServiceConnection connService = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            printService = null;
            mCallBack.onDisConnect("断开成功", true);
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            printService = IPrintService.Stub.asInterface(service);
            mCallBack.onConnect("连接成功", true);
        }
    };


    @Override
    public void printString(List<AttributeBean> testList, int width) {

    }

}
